package com.yoso.shop.infrastructure.utils;

import com.yoso.shop.infrastructure.config.InitConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author shizejin
 * @date 2022/2/23
 * @description:
 */
@Component
public class UploadUtils {
    @Autowired
    private InitConfig initConfig;

    /**
     * 获取静态资源根路径(真实路径)
     *
     * @return eg: C:/images/
     */
    public String getStaticResourceRootDirPath() {
        String staticFolderPath = initConfig.getStaticFolderPath();
        if (!StringUtils.endsWith(staticFolderPath, File.separator)) {
            staticFolderPath += File.separator;
        }
        return staticFolderPath;
    }

    /**
     * 静态资源映射路径(访问路径)
     *
     * @return eg:http://192.168.45.40:3326/static/
     */
    public String getStaticRequestPath() {
//        /path -> /path/
        String staticRequestPath = initConfig.getStaticRequestPath();
        if (!StringUtils.endsWith(staticRequestPath, File.separator)) {
            staticRequestPath += File.separator;
        }
//         /path/ -> path/
        if (StringUtils.startsWith(staticRequestPath, File.separator)) {
            staticRequestPath = staticRequestPath.substring(1);
        }
        return "http://" + initConfig.getIpv4() + ":" + initConfig.getPort() + File.separator + staticRequestPath;
    }

    /**
     * @param path     图片所在的相对路径  eg: icon
     * @param fileName 文件名 eg: hello.png
     */
    public Path getPath(String path, String fileName) {
        return Paths.get(getStaticResourceRootDirPath() + path, fileName);
    }

    /**
     * @param path     图片所在的相对路径  eg: icon
     * @param fileName 文件名 eg: hello.png
     * @return eg: http://localhost:3326/static/icon/hello.png
     */
    public String buildPhotoUrl(String path, String fileName) {
        String result = getStaticRequestPath() + path + File.separator + fileName;
        return parseUrl(result);
    }

    /**
     * @param url http://localhost:3326\static\icon\hello.png
     * @return http://localhost:3326/static/icon/hello.png
     */
    public String parseUrl(String url) {
        if (StringUtils.contains(url, "\\")) {
//            在正则表达式中使用4个\ 匹配字符串中出现的1个 \
            url = StringUtils.replaceAll(url, "\\\\", "/");
        }
        return url;
    }
}
